<template>
  <div id="subject-select-head">
    <div class="contaier">
      <div class="title-box df bc br">
        <!-- 院校头部 -->
        <div
          class="left-progress df"
          :style="ruleType == 1 ? 'flex-direction: row-reverse' : ''"
        >
          <!-- 综合匹配率，适用于 ruleType 为 0 的情况 -->
          <div class="progress" v-if="ruleType == 0">
            <el-progress
              type="circle"
              :percentage="total ? total : calculatedPercentage"
            >
              <template #default>
                <div style="color: var(--color-text)">
                  <div class="percentage-value" style="margin: 0 0 10px 0">
                    {{ total ? total + '%' : calculatedMatchRate }}
                  </div>
                  <div class="percentage-label">综合匹配率</div>
                </div>
              </template>
            </el-progress>
          </div>

          <!-- 分别显示院校和专业匹配率，适用于 ruleType 为 1 的情况 -->
          <div class="progress2" v-if="ruleType == 1">
            <!-- 院校匹配率部分 -->
            <div class="progress2-item">
              <el-progress
                type="circle"
                :percentage="yxMatchRate ? yxMatchRate : collegeMatchPercentage"
              >
                <template #default>
                  <div style="color: var(--color-text)">
                    <div class="percentage-value" style="margin: 0 0 10px 0">
                      {{ yxMatchRate ? yxMatchRate : collegeMatchPercentage }}%
                    </div>
                  </div>
                  <div class="percentage-label">院校匹配率</div>
                </template>
              </el-progress>
              <div class="percentage-right">
                <div class="percentage-label">院校总数: {{ collegeTotal }}</div>
                <div class="percentage-label">
                  匹配院校: {{ collegeMatched }}
                </div>
              </div>
            </div>

            <!-- 专业匹配率部分 -->
            <div class="progress2-item">
              <el-progress
                type="circle"
                :percentage="zyMatchRate ? zyMatchRate : majorMatchPercentage"
              >
                <template #default>
                  <div style="color: var(--color-text)">
                    <div class="percentage-value" style="margin: 0 0 10px 0">
                      {{ zyMatchRate ? zyMatchRate : majorMatchPercentage }}%
                    </div>
                  </div>
                  <div class="percentage-label">专业匹配率</div>
                </template>
              </el-progress>
              <div class="percentage-right">
                <div class="percentage-label">专业总数: {{ majorTotal }}</div>
                <div class="percentage-label">匹配专业: {{ majorMatched }}</div>
              </div>
            </div>
          </div>
          <div
            :class="
              ruleType == 0 ? 'progress-text-right0' : 'progress-text-right1'
            "
          >
            <div style="margin: 0 30px">
              <div class="f12 text-color">
                <span>{{ ruleType == 0 ? '最优组合方案' : '我的选科' }}</span>
                {{ scheme }}
              </div>

              <div class="df">
                <div class="df curpoin">
                  <!-- 第一个下拉 -->
                  <el-dropdown
                    @command="(item) => handleDropdownSelect(item, 1)"
                    trigger="click"
                    :hide-on-click="true"
                  >
                    <span class="el-dropdown-link">
                      {{ selectedLabel1 }}
                      <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          :command="item"
                          v-for="item in dropdown1Options"
                          :key="item.id"
                          :disabled="isOptionDisabled(item.subName, 1)"
                        >
                          {{ item.subName }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <!-- 下拉2 -->
                <div class="df curpoin class-item">
                  <!-- 第二个下拉 -->
                  <el-dropdown
                    @command="(item) => handleDropdownSelect(item, 2)"
                    trigger="click"
                    :hide-on-click="true"
                  >
                    <span class="el-dropdown-link">
                      {{ selectedLabel2 }}
                      <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          :command="item"
                          v-for="item in dropdown2Options"
                          :key="item.id"
                          :disabled="isOptionDisabled(item.subName, 2)"
                        >
                          {{ item.subName }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <!-- 下拉3 -->
                <div class="df curpoin class-item">
                  <!-- 第三个下拉 -->
                  <el-dropdown
                    @command="(item) => handleDropdownSelect(item, 3)"
                    trigger="click"
                    :hide-on-click="true"
                  >
                    <span class="el-dropdown-link">
                      {{ selectedLabel3 }}
                      <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          :command="item"
                          v-for="item in dropdown3Options"
                          :key="item.id"
                          :disabled="isOptionDisabled(item.subName, 3)"
                        >
                          {{ item.subName }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </div>
            <div
              style="margin: 0 10px"
              :style="ruleType == 1 ? 'margin-top: 10px' : ''"
            >
              <div>学科关联性</div>
              <div style="text-align: center" class="font-weight-bold">
                {{ get(matchRateInfo, 'related', '-') }}
              </div>
            </div>
          </div>
        </div>

        <div
          class="right-selected-box df"
          style="justify-content: space-evenly"
        >
          <div>
            <div class="df curpoin">
              <el-dropdown trigger="click" :hide-on-click="true">
                <span class="el-dropdown-link">
                  已选
                  <span style="color: var(--color-text)">
                    {{ get(selectMarjorList, 'length', 0) }}
                  </span>
                  专业<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="item in selectMarjorList"
                      :key="item.id"
                      >{{ item.majorName }}
                      <el-icon
                        style="margin-left: 10px"
                        @click.stop="handleRemove(item, 0)"
                        ><Close
                      /></el-icon>
                    </el-dropdown-item>
                    <div
                      class="clear-buttton curpoin"
                      @click="handleClearAll(false)"
                    >
                      清空已选
                    </div>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="df curpoin">
              <el-dropdown trigger="click" :hide-on-click="true">
                <span class="el-dropdown-link">
                  已选
                  <span style="color: var(--color-text)">
                    {{ get(selectCollegeList, 'length', 0) }}
                  </span>
                  院校<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="item in selectCollegeList"
                      :key="item.id"
                      >{{ item.collegeName }}
                      <el-icon
                        style="margin-left: 10px"
                        @click.stop="handleRemove(item, 1)"
                        ><Close /></el-icon
                    ></el-dropdown-item>
                    <div
                      class="clear-buttton curpoin"
                      @click="handleClearAll(true)"
                    >
                      清空已选
                    </div>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          <div class="my-btn f14 curpoin" @click="handleSubmit">保存方案</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch, watchEffect } from 'vue';
import bus from '@/utils/bus';
import { useStore } from 'vuex';
import {
  mapBestCombine,
  updateSubjectData,
  updateDropdownOptions,
  getLableName,
  getLableCode,
  handleDropdownSelectFn,
  isOptionDisabledFn,
} from './utils';
import { get } from 'lodash';

const store = useStore();
const emits = defineEmits(['handleSubmit', 'handleSelectResSave']);

const {
  subjectSelectList,
  isMajor,
  ruleType,
  matchRateInfo,
  zyMatchRate,
  yxMatchRate,
  xkType,
} = defineProps({
  collegeGroupRatio: {
    type: Number,
    default: 0,
  },
  collegeRelated: {
    type: String,
    default: '',
  },
  zyMatchRate: {
    type: [String, Number],
    default: '',
  },
  yxMatchRate: {
    type: [String, Number],
    default: '',
  },
  xkType: {
    type: [String, Number],
    default: '',
  },
  subjectSelectList: {
    type: Array,
    default: () => [],
  },
  isMajor: {
    type: Boolean,
    default: false,
  },
  // 路由传参不同页面 0智能选科，1自主选科，3选科查询
  ruleType: {
    type: [Number, String],
    retquied: true,
    default: 0, // 默认值
  },
  matchRateInfo: {
    type: Object,
    default: () => ({}),
  },
});
// 根据 ruleType 和 isMajor 动态选择匹配数据
const selectedMatch = computed(() => {
  if (ruleType == 1) {
    return {
      majorMatch: get(matchRateInfo, 'percentMajorMatch', '0 / 0 / 0%'),
      collegeMatch: get(matchRateInfo, 'percentCollegeMatch', '0 / 0 / 0%'),
    };
  } else {
    const matchKey = isMajor ? 'percentMajorMatch' : 'percentCollegeMatch';
    return get(matchRateInfo, matchKey, '0 / 0 / 0%');
  }
});

// 综合匹配率 (仅适用于 ruleType 为 0)
const calculatedPercentage = computed(() => {
  if (ruleType == 1) return null;
  const parts = selectedMatch.value.split(' / ');
  return parseInt(parts[2]) || 0;
});
const calculatedMatchRate = computed(() => {
  if (ruleType == 1) return null;
  return `${calculatedPercentage.value || 0}%`;
});

// 院校匹配数据 (仅适用于 ruleType 为 1)
const collegeMatchInfo = computed(() =>
  selectedMatch.value.collegeMatch.split(' / '),
);
const collegeMatched = computed(() => collegeMatchInfo.value[0] || '0');
const collegeTotal = computed(() => collegeMatchInfo.value[1] || '0');
const collegeMatchPercentage = computed(
  () => parseInt(collegeMatchInfo.value[2]) || 0,
);

// 专业匹配数据 (仅适用于 ruleType 为 1)
const majorMatchInfo = computed(() =>
  selectedMatch.value.majorMatch.split(' / '),
);
const majorMatched = computed(() => majorMatchInfo.value[0] || '0');
const majorTotal = computed(() => majorMatchInfo.value[1] || '0');
const majorMatchPercentage = computed(
  () => parseInt(majorMatchInfo.value[2]) || 0,
);
// 在智能选科根据专业或者院校，表格选择时生成对应匹配率
const total = computed(() => (isMajor ? zyMatchRate : yxMatchRate));
// 右侧回显选中的院校和专业
const selectCollegeList = computed(
  () => store.getters.znxkInfo.selectCollegeList,
);
const selectMarjorList = computed(
  () => store.getters.znxkInfo.selectMarjorList,
);
// 下拉1、2、3的默认值
const selectedLabel1 = ref('');
const selectedLabel2 = ref('');
const selectedLabel3 = ref('');
// 下拉框选项
const dropdown1Options = ref([]);
const dropdown2Options = ref([]);
const dropdown3Options = ref([]);

// 最佳组合方案
const scheme = computed(() => {
  return [
    selectedLabel1.value,
    selectedLabel2.value,
    selectedLabel3.value,
  ].join('+');
});
const storeInfo = computed(() =>
  isMajor ? 'znxk/changeZySgId' : 'znxk/changeYxSgId',
);

// 通用下拉选择事件处理函数
const handleDropdownSelect = (item, labelIndex) => {
  handleDropdownSelectFn(item, labelIndex, {
    selectedLabel1,
    selectedLabel2,
    selectedLabel3,
    store,
    getLableName,
    getLableCode,
    storeInfo,
    isMajor,
  });
};

// 检查选项是否应当被禁用
const isOptionDisabled = (itemSubName, currentLabelIndex) => {
  return isOptionDisabledFn(itemSubName, currentLabelIndex, xkType.value, {
    selectedLabel1,
    selectedLabel2,
    selectedLabel3,
  });
};
// 切换左上角省份
bus.on('updataXkType', () => {
  window.location.reload();
});

// 清除全部已选择的院校或专业
const handleClearAll = (isCollege) => {
  dispatchStore(isCollege, []);
};

// 删除已选择的院校或专业
const handleRemove = (item, isCollege) => {
  const list = isCollege ? selectCollegeList.value : selectMarjorList.value;
  const updatedList = list.filter(({ id }) => id !== item.id);
  dispatchStore(isCollege, updatedList);
};

// 更新store对应专业和院校的值
const dispatchStore = (isCollege, data) => {
  const action = isCollege
    ? 'znxk/changeSelectCollegeList'
    : 'znxk/changeSelectMarjorList';
  store.dispatch(action, data);
};
// 保存方案
const handleSubmit = () => {
  emits('handleSelectResSave');
};
const transFormData = ref([]);
// 监听 subjectSelectList 的变化并调用 updateDropdownOptions 更新选项
watch(
  () => subjectSelectList,
  () => {
    // 调用更新函数获取处理后的数据
    transFormData.value = updateDropdownOptions(
      isMajor,
      ruleType,
      subjectSelectList,
      xkType,
    );
    // 获取store的值
    const { yxSgID, zySgID, isTableSelectZy, isTableSelectYx } =
      store.getters.znxkInfo;
    const selectedIDs = isMajor ? zySgID : yxSgID;
    const flag = isMajor ? isTableSelectZy : isTableSelectYx;
    handleSelection(selectedIDs, flag);
  },
  { deep: true },
);
// 更新选择项逻辑
const handleSelection = (selectedIDs, flag) => {
  // 如果有选中的 IDs 且 flag 为 false，则直接更新
  if (selectedIDs.length && !flag) {
    updateSelection(selectedIDs);
    return;
  }

  // 如果 transFormData 有数据，则处理默认选择逻辑
  if (transFormData.value.length) {
    const { defaultIDs, defaultLabels } = getDefaultSelection();

    // 根据 ruleType 判断是否使用默认选择
    if (ruleType == 1) {
      updateSelection(selectedIDs.length ? selectedIDs : defaultIDs);
      // 更新选择标签
      if (!selectedIDs.length) {
        [selectedLabel1.value, selectedLabel2.value, selectedLabel3.value] =
          defaultLabels;
      }
    } else {
      // 直接使用默认选择
      updateSelection(defaultIDs);
      [selectedLabel1.value, selectedLabel2.value, selectedLabel3.value] =
        defaultLabels;
    }
  }
};
// 获取默认选择项
const getDefaultSelection = () => {
  const defaultSelection = transFormData.value.slice(0, 3);
  const defaultIDs = defaultSelection.map((item) => item.id);
  const defaultLabels = defaultSelection.map((item) => item.subName);
  return { defaultIDs, defaultLabels };
};
// 封装选择更新逻辑
const updateSelection = (ids) => {
  commitSelectedIDs(ids);
  updateLabelsFromIDs(ids);
};

// 监听已选列表变化，统计选中课程id的出现次数
watch(
  () => [
    store.getters.znxkInfo.selectCollegeList,
    store.getters.znxkInfo.selectMarjorList,
  ],
  ([newCollegeList, newMajorList]) => {
    const { isManualSelectYx, isManualSelectZy } = store.getters.znxkInfo;
    // 根据 isMajor 选择要更新的 map 和手动选择标志
    const isManualSelect = isMajor ? isManualSelectZy : isManualSelectYx;
    const selectedMap = isMajor
      ? mapBestCombine(newMajorList)
      : mapBestCombine(newCollegeList);
    // 如果是手动选择，提前返回
    if (isManualSelect) return;
    updateSubjectData(selectedMap, subjectSelectList);
  },
  { deep: true },
);

// 动态设置下拉框选项
watchEffect(() => {
  // 对应省份的科目数据，并且赋值给3个科目下拉
  if (!subjectSelectList.length) return;
  // 定义各下拉框的过滤条件
  const filterConditions =
    xkType == 3
      ? [
          (item) => [1, 4].includes(item.id),
          (item) => [2, 3, 5, 6].includes(item.id),
          (item) => [3, 2, 5, 6].includes(item.id),
        ]
      : [() => true, () => true, () => true]; // 如果 xkType 不为 3，则不过滤

  // 循环应用过滤条件
  [dropdown1Options, dropdown2Options, dropdown3Options].forEach(
    (dropdown, index) => {
      dropdown.value = subjectSelectList.filter(filterConditions[index]);
    },
  );
});

// 监听 isMajor 的变化，切换专业和院校模式
watch(
  () => isMajor,
  (isZy) => {
    const { isManualSelectYx, isManualSelectZy, yxSgID, zySgID } =
      store.getters.znxkInfo;

    // 获取对应的手动选择状态和 ID 列表
    const isManualSelect = isZy ? isManualSelectZy : isManualSelectYx;
    const selectedIDs = isZy ? zySgID : yxSgID;

    // 根据不同情况更新标签
    if (isManualSelect || selectedIDs.length) {
      // 如果是手动选择状态或有已选 ID 列表，更新标签
      updateLabelsFromIDs(selectedIDs);
    } else if (transFormData.value.length) {
      // 设置 commitSelectedIDs 为 transFormData 中前三项的 ID
      const defaultIDs = transFormData.value.slice(0, 3).map((item) => item.id);
      updateSelection(defaultIDs);
      // 使用 transFormData 的前三项作为默认标签
      [selectedLabel1.value, selectedLabel2.value, selectedLabel3.value] =
        transFormData.value.slice(0, 3).map((item) => item.subName);
    }
  },
);

// 提取 Vuex 获取和提交操作
const commitSelectedIDs = (ids) => {
  const storeInfo = isMajor ? 'znxk/set_zysgId' : 'znxk/set_yxsgId';
  ids.forEach((id, index) => {
    store.commit(storeInfo, { index, id });
  });
};

// 定义一个函数来简化标签更新操作
const updateLabelsFromIDs = (ids) => {
  selectedLabel1.value = getLableName[ids[0]];
  selectedLabel2.value = getLableName[ids[1]];
  selectedLabel3.value = getLableName[ids[2]];
};
</script>

<style lang="scss" scoped src="./subjectSelectHead.scss"></style>
